package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.FunctionalityPartsCheckBCSM;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.EvaluateCheckItemView2;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/** Created by Michael on 2017/4/12 15:43. */
public class FunctionalityPartsCheckFragment extends BaseFragment
    implements EvaluateWorkflowActivity.OnOutActionListener,
        EvaluateCheckItemView2.OnPhotoIconClicked,
        CompoundButton.OnCheckedChangeListener,
        OssService.onImageProcessedResultListener,
        ImageSelectDialog.ImageSelectListener {

  public static final int PAGE_INDEX = 13;
  private static final String TAG = FunctionalityPartsCheckFragment.class.getSimpleName();
  private static final int PREVIEW_IMG_REQUEST = 0xff10;
  private static int uploadImgCounter = 0;

  @BindView(R.id.cb_all_check_ok)
  CheckBox cbAllCheckOk;

  @BindView(R.id.check_item_47)
  EvaluateCheckItemView2 checkItem47;

  @BindView(R.id.check_item_48)
  EvaluateCheckItemView2 checkItem48;

  @BindView(R.id.check_item_49)
  EvaluateCheckItemView2 checkItem49;

  @BindView(R.id.check_item_50)
  EvaluateCheckItemView2 checkItem50;

  @BindView(R.id.check_item_51)
  EvaluateCheckItemView2 checkItem51;

  @BindView(R.id.check_item_52)
  EvaluateCheckItemView2 checkItem52;

  @BindView(R.id.check_item_53)
  EvaluateCheckItemView2 checkItem53;

  @BindView(R.id.check_item_54)
  EvaluateCheckItemView2 checkItem54;

  @BindView(R.id.check_item_55)
  EvaluateCheckItemView2 checkItem55;

  @BindView(R.id.check_item_56)
  EvaluateCheckItemView2 checkItem56;

  @BindView(R.id.check_item_57)
  EvaluateCheckItemView2 checkItem57;

  @BindView(R.id.check_item_58)
  EvaluateCheckItemView2 checkItem58;

  @BindView(R.id.check_item_59)
  EvaluateCheckItemView2 checkItem59;

  @BindView(R.id.rl_bcsm)
  RelativeLayout rlBcsm;

  @BindView(R.id.tv_previous_step)
  TextView tvPreviousStep;

  @BindView(R.id.tv_next_step)
  TextView tvNextStep;

  @BindView(R.id.ll_content)
  LinearLayout llContent;

  @BindView(R.id.iv_goto_top)
  ImageView ivGotoTop;

  @BindView(R.id.sc_content)
  ScrollView scContent;

  private ArrayList<EvaluateCheckItemView2> checkItems;
  private List<EvaluateDetailResult2.DetectionBean.PartsBean> partsBeanList;

  private ImageSelectDialog imgSelectDialog;
  private ImageCaptureManager captureManager;
  private Runnable mTask;

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_frag_functionality_parts_check, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {

    checkItems = new ArrayList<>(10);
    checkItems.add(checkItem47);
    checkItems.add(checkItem48);
    checkItems.add(checkItem49);
    checkItems.add(checkItem50);
    checkItems.add(checkItem51);
    checkItems.add(checkItem52);
    checkItems.add(checkItem53);
    checkItems.add(checkItem54);
    checkItems.add(checkItem55);
    checkItems.add(checkItem56);
    checkItems.add(checkItem57);
    checkItems.add(checkItem58);
    checkItems.add(checkItem59);

    captureManager = new ImageCaptureManager(getActivity());
  }

  @Override
  protected void initView() {

    ivGotoTop.setOnClickListener(this);
    rlBcsm.setOnClickListener(this);
    tvPreviousStep.setOnClickListener(this);
    tvNextStep.setOnClickListener(this);

    //       设置照相机图标点击事件回调
    for (EvaluateCheckItemView2 checkItem : checkItems) {
      checkItem.setOnPhotoIconClickedListener(this);
    }

    cbAllCheckOk.setOnCheckedChangeListener(this);
  }

  @Override
  protected void initData() {}

  @Override
  public void onResume() {
    super.onResume();
    displayInfo();
  }

  private void displayInfo() {
    if (null != MyApplication.getInstance().getEvaluateResult()
        && null != MyApplication.getInstance().getEvaluateResult().getDetection()
        && null != MyApplication.getInstance().getEvaluateResult().getDetection().getParts()) {

      partsBeanList = MyApplication.getInstance().getEvaluateResult().getDetection().getParts();
      if(partsBeanList == null || partsBeanList.size() == 0){
        //默认全选
        cbAllCheckOk.setChecked(true);
      }else{
        for (int i = 0; i < partsBeanList.size(); i++) {
          checkItems.get(partsBeanList.get(i).getId() - 47).setTag(partsBeanList.get(i));
          checkItems
                  .get(partsBeanList.get(i).getId() - 47)
                  .setCheckedIndex(partsBeanList.get(i).getStatus());
          checkItems
                  .get(partsBeanList.get(i).getId() - 47)
                  .setPhotoBtnState(!TextUtils.isEmpty(partsBeanList.get(i).getImage()));
          checkItems
                  .get(partsBeanList.get(i).getId() - 47)
                  .setRemarksDesc(partsBeanList.get(i).getMark());
        }
      }
    }else{
      //默认全选
      cbAllCheckOk.setChecked(true);
    }
  }

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.iv_goto_top:
        scContent.smoothScrollTo(0, 0);
        break;
      case R.id.rl_bcsm:
        startActivity(new Intent(getActivity(), FunctionalityPartsCheckBCSM.class));
        break;
      case R.id.tv_next_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToNextPage();
              }
            });
        break;
      case R.id.tv_previous_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToPreviousPage();
              }
            });

        break;
      default:
        break;
    }
  }

  /** 进入图片选择页面 */
  private void pickPhoto() {
    PhotoPicker.builder().setPhotoCount(1).start(getActivity(), this);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case PhotoPicker.REQUEST_CODE:
        if (data != null
            && null != data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0)) {

          String localImgPath =
              data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
          Log.e(
              TAG,
              "onActivityResult: " + localImgPath + " EvaluateCheckItem : " + llContent.getTag());

          EvaluateCheckItemView2 checkItem = checkItems.get((int) llContent.getTag() - 47);
          checkItem.setImgPath(localImgPath);

          if (null == checkItem.getTag()) {
            checkItem.setTag(
                new EvaluateDetailResult2.DetectionBean.PartsBean(
                    (int) llContent.getTag(),
                    checkItem.getCheckedIndex(),
                    checkItem.getRemarkDesc(),
                    localImgPath));
          } else {
            ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItem.getTag())
                .setImage(localImgPath);
          }
          checkItem.setPhotoBtnState(true);
        }

        break;

      case ImageCaptureManager.REQUEST_TAKE_PHOTO:
        if (resultCode == RESULT_OK) {
          captureManager.galleryAddPic();

          String path = captureManager.getCurrentPhotoPath();

          EvaluateCheckItemView2 checkItem = checkItems.get((int) llContent.getTag() - 47);
          checkItem.setImgPath(path);

          if (null == checkItem.getTag()) {
            checkItem.setTag(
                new EvaluateDetailResult2.DetectionBean.PartsBean(
                    (int) llContent.getTag(),
                    checkItem.getCheckedIndex(),
                    checkItem.getRemarkDesc(),
                    path));
          } else {
            ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItem.getTag()).setImage(path);
          }
          checkItem.setPhotoBtnState(true);
        }

        break;

      case PREVIEW_IMG_REQUEST:
        if (data == null) {
          return;
        }

        boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
        Log.e(TAG, "onActivityResult: " + deleteImg);

        if (deleteImg) {
          checkItems.get((int) llContent.getTag() - 47).setImgPath("");
          checkItems.get((int) llContent.getTag() - 47).setCheckedIndex(4);
          ((EvaluateDetailResult2.DetectionBean.PartsBean)
                  checkItems.get((int) llContent.getTag() - 47).getTag())
              .setImage("");
          checkItems.get((int) llContent.getTag() - 47).setPhotoBtnState(false);
        }
        break;

      default:
        break;
    }
  }

  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if (isChecked) {

      for (EvaluateCheckItemView2 checkItem : checkItems) {

        if (checkItem.getCheckedIndex() != 0) {
          checkItem.setCheckedIndex(0);
        }
      }
    } else {

      //                如果是手动选中，则全部反选
      for (EvaluateCheckItemView2 checkItem : checkItems) {

        if (checkItem.getCheckedIndex() != 4) {
          checkItem.setCheckedIndex(4);
        }
      }
    }
  }

  @Override
  public void takePhoto(int evaluateItemIndex) {

    llContent.setTag(evaluateItemIndex);

    Log.e(TAG, "takePhoto: " + evaluateItemIndex);

    if (null != checkItems.get(evaluateItemIndex - 47).getTag()
        && !TextUtils.isEmpty(
            ((EvaluateDetailResult2.DetectionBean.PartsBean)
                    checkItems.get(evaluateItemIndex - 47).getTag())
                .getImage())) {

      //          有照片，预览照片
      Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
      intent.putExtra(
          "IMG_PATH",
          ((EvaluateDetailResult2.DetectionBean.PartsBean)
                  checkItems.get(evaluateItemIndex - 47).getTag())
              .getImage());
      this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);

    } else {
      showImgSelectDialog("");
    }
  }

  public void showImgSelectDialog(String titleStr) {

    if (null == imgSelectDialog) {
      imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
    } else {
      imgSelectDialog.setTitleStr(titleStr);
    }
    imgSelectDialog.show();
  }

  @Override
  public void onItemChecked(int cbIndex, int evaluateItemIndex) {

    EvaluateCheckItemView2 checkItem = checkItems.get(evaluateItemIndex - 47);

    if (null == checkItems.get(evaluateItemIndex - 47).getTag()) {
      checkItem.setTag(
          new EvaluateDetailResult2.DetectionBean.PartsBean(
              evaluateItemIndex, cbIndex, checkItem.getRemarkDesc(), checkItem.getImgPath()));
    } else {
      ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItem.getTag()).setStatus(cbIndex);
    }
  }

  @Override
  public void onSaveEvaluateResult(Runnable task) {

    if (null != task) {
      mTask = task;
    }

    for (int i = 0; i < checkItems.size(); i++) {

      if (null != checkItems.get(i).getTag()
          && ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                  .getStatus()
              != 4
          && !TextUtils.isEmpty(
              ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                  .getImage())
          && !((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
              .getImage()
              .startsWith("http")) {

        uploadImage();
        return;
      }
    }

    //      如果没有选择照片，则不需上传，直接保存结果
    saveData();
  }

  private void uploadImage() {

    Gson gson = new Gson();

    for (int i = 0; i < checkItems.size(); i++) {

      if (null != checkItems.get(i).getTag()
          && ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                  .getStatus()
              != 4
          && !TextUtils.isEmpty(
              ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                  .getImage())) {

        Log.e(TAG, "onSaveEvaluateResult: 带上传图片" + gson.toJson(checkItems.get(i).getTag()));

        if (!((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
            .getImage()
            .startsWith("http")) {

          // 上传图片
          MyApplication.getInstance()
              .getOssService(this)
              .asyncPutImage(
                  OssService.getOssObjectInfo(true),
                  ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                      .getImage(),
                  String.valueOf(
                      ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                          .getId()));

          ++uploadImgCounter;
          Log.e(TAG, "onSaveEvaluateResult: " + uploadImgCounter);
          showDialog();
        }
      }
    }
  }

  private void saveData() {

    List<EvaluateDetailResult2.DetectionBean.PartsBean> tempList = new ArrayList<>();

    for (int i = 0; i < checkItems.size(); i++) {

      if (null != checkItems.get(i).getTag()
          && ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
                  .getStatus()
              != 4) {
        ((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag())
            .setMark(checkItems.get(i).getRemarkDesc());
        tempList.add(((EvaluateDetailResult2.DetectionBean.PartsBean) checkItems.get(i).getTag()));
      }
    }

    String jsonStr =
        new StringBuilder("{\"parts\":").append(new Gson().toJson(tempList)).append("}").toString();

    Log.e(TAG, "saveData: 最后结果 ：  " + jsonStr);

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
    params.put("detection", jsonStr);

    if (MyApplication.getInstance().getEvaluateResult() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
      int[] iroute = new int[15];
      iroute[PAGE_INDEX] = 1;
      String json = new Gson().toJson(iroute);
      Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
      params.put("iroute", json.substring(1, json.length() - 1));
    } else {
      MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
      String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
      params.put("iroute", json.substring(1, json.length() - 1));
      Log.e(
          TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
    }

    Log.e(TAG, "saveData: 发送请求 :  " + MyApplication.getInstance().getEvaluateResult().getAid());

    //        根据评估类型进行保存或编辑
    int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

    //       保存新创建、未上传待评估数据
    if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new RespCallback<EvaluateDetailResult2>() {

            @Override
            protected void onRequestFailed(String msg) {
              SToast.show(msg);
              if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                mTask.run();
                mTask = null;
              }
            }

            @Override
            protected void onSuccess(EvaluateDetailResult2 data) {

              if (null != data) {

                MyApplication.getInstance().setEvaluateResult(data);
                //                                SToast.show("保存成功");
                Log.e(TAG, "onSuccess: " + "保存成功!");
                displayInfo();

                if (null != mTask) {
                  mTask.run();
                  mTask = null;
                }

              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });

    } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {

              try {

                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code") == 1) {
                  //                            SToast.show("保存成功", Gravity.CENTER);

                  Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));

                  if (null != mTask) {
                    mTask.run();
                    mTask = null;
                  }

                } else {
                  SToast.show(obj.optString("msg"));
                  if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                    mTask.run();
                    mTask = null;
                  }
                }

              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    }
  }

  private void goToPreviousPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(DiPanCheckFragment.PAGE_INDEX);
  }

  private void goToNextPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CheckResultPz.PAGE_INDEX);
  }

  @Override
  public void onUploadOk(String imgUrl, Object tag) {

    Log.e(TAG, "onUploadOk: 上传成功 ： " + imgUrl);

    ((EvaluateDetailResult2.DetectionBean.PartsBean)
            checkItems.get(Integer.valueOf((String) tag) - 47).getTag())
        .setImage(imgUrl);

    --uploadImgCounter;

    if (uploadImgCounter == 0) {
      saveData();
    }
  }

  @Override
  public void onUploadFailed() {
    SToast.show("图片上传失败！请重试");
  }

  private void openSystemCamera() {
    Intent intent = null;
    try {
      intent = captureManager.dispatchTakePictureIntent();
      startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onTakePhotoWithSystemCamera() {
    openSystemCamera();
  }

  @Override
  public void onSelectImgOnGallery() {
    pickPhoto();
  }
}
